const db = require('../db/connMysql');

const powerDao = {
    /*
     * 检查用户是否含有某个权限
     */
    async checkPowerByUid(uid, powerName) {
        let result = await new Promise((resolve, reject) => {
            db.getConnection((err, connection) => {
                if (err) {
                    // 连不上数据库
                    reject(err);
                    return ;
                }
                let sql = `select
                               uid, powerId
                           from
                               UserPower
                           where UserPower.uid = ? and UserPower.powerId = (
                               select powerId from Power where name = ? LIMIT 1
                           ) Limit 1`;
                connection.query(sql, [uid, powerName], function (err, result) {
                    if (err) {
                        // 连上数据库之后，执行sql时发生错误
                        connection.release();
                        reject(err);
                        return ;
                    }
                    connection.release();
                    resolve(result);
                });
            });
        });
        return result;
    },
    /*
     * 获取用户权限列表
     */
    async getUserPowerList(uid) {
        let result = await new Promise((resolve, reject) => {
            db.getConnection((err, connection) => {
                if (err) {
                    // 连不上数据库
                    reject(err);
                    return ;
                }
                let sql = `select
                               p.powerId as powerId,
                               p.name as powerName
                           from UserPower as up
                           left join Power as p on up.powerId = p.powerId
                           where up.uid = ?`;
                connection.query(sql, [uid], function (err, result) {
                    if (err) {
                        // 连上数据库之后，执行sql时发生错误
                        connection.release();
                        reject(err);
                        return ;
                    }
                    connection.release();
                    resolve(result);
                });
            });
        });
        return result;
    }
};

module.exports = powerDao;
